/*####################################################################################
  CLASS : mydojo.dijix.AxGrid
  =============================
  - An AJAX enabled grid widget with toolbar
  
  - Things you would want to override and call "this.inherited" from derived class  
    1. createToolBar - to add extra button on the toolbar
    2. enableButtons - to take control on what buttons to enable after grid data is rendered 
    3. render - to get control over how rendering is done when server response is received and of type "view widget(vw)"
  [Author:PMS]  
  ####################################################################################*/
  
dojo.provide("mydojo.dijix.AxGrid");

dojo.require("mydojo.dijix.SimpleGrid");
dojo.require("mydojo.core.AjaxHandler");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.form.Button");
dojo.require("dijit.Toolbar");

dojo.declare("mydojo.dijix.AxGrid", [ dijit.layout.ContentPane , mydojo.core.AjaxHandler ] , {
		
		toolbarStruct	: [ 'r','a','e','d','et' ],
		// Region references...
		//struct 			: [], // depreciated.... seems like indexed array is not working when multiple DbGrid used in same TabView
		gridStruct 	: [	{name: 'First Name' }, 
						{name: 'Last Name' }, 
						{name: 'Address' }, 
						{name: 'This is'}, 
						{name: 'AxGrid'}
					  ],
		// internal widget refs....
		bcWt			: "",
		toolWt			: "",
		gridWt			: "",
		footerWt		: "",
		ttdWt			: "",
		trWt			: "",
		// Events...	
		refreshUrl		: "",		// REFRESH grid with data from server
				
		addUrl			: "",		// ADD a row from the grid
		addDlgTitle		: "",
		addDlgAction	: "",
		addDlgHasFile	: false,
		addDlgWidth		: "360px",
		
		editUrl			: "",		// EDIT a row from the grid
		editDlgTitle	: "",
		editDlgAction	: "",
		editDlgHasFile	: false,
		editDlgWidth	: "360px",
		
		deleteUrl		: "",		// DELETE row(s) from the grid
		emptyUrl		: "",		// EMPTY table
		
		refreshOnCreate	: false,		
		editOnDbClick	: false,
		
		// ======================================================================
		//	Post create widget
		// ----------------------------------------------------------------------
		postCreate: function() {		
			//console.log("---> AxGrid.postCreate()");
			this.inherited(arguments);	
			
			// create BC
			var rootNode = document.createElement("div");			
			this.bcWt = new dijit.layout.BorderContainer( {id:this.id+"_bc" , style:"width:100%;height:100%"} , rootNode );
			this.domNode.appendChild(this.bcWt.domNode);
			console.log("title = " + this.title);
			// create TOP CP						
			var height = this.title? 52 : 32;
			this.toolWt = new dijit.layout.ContentPane( {id:this.id+"_top" , style:"background:#A0C1D9;height:"+height+"px;overflow:hidden" , region:"top"});
			this.bcWt.addChild(this.toolWt);
			if(this.title){
				var d = document.createElement("div");
				d.innerHTML = this.title;
				d.style.cssText = "width:100%; padding:5px;; background-color:#42769D;font-size:12px;font-weight:bold;color:#FFFFFF";
				this.toolWt.domNode.appendChild(d);
			}
				
			
			// create CENTER CP	-- this is actually SimpleGrid					
			this.gridWt = new mydojo.dijix.SimpleGrid( {id:this.id+"_cen" , region:"center" , data:this.data , gridStruct:this.gridStruct});
			this.bcWt.addChild(this.gridWt);
						
			// create BOTTOM CP
			this.footerWt = new dijit.layout.ContentPane( {id:this.id+"_btt" , style:"background:#BDD5E4;height:20px;border-bottom:0px solid #000" , region:"bottom"});
			this.bcWt.addChild(this.footerWt);
			
			// create toolbar						
			this.createToolbar();					
					
			// create footer
			this.trWt = document.createElement("span");
			this.trWt.id = this.id+"_totRec";
			this.footerWt.setContent("<span class='text2'>Total:</span>");
			this.footerWt.domNode.appendChild(this.trWt);
			
			this.bcWt.startup();
			this.bcWt.layout();	
			
			this.updateTotalRecs();			
			
			// if view render is response type then call this render
			this.renderView = this.render;
			
			if( this.refreshOnCreate )
				this.rClicked();									
			
			if( this.editOnDbClick )	
				dojo.connect( this.gridWt , "onDoubleClick" , this , "eClicked" );		
		},
		// ======================================================================
		//	Render response from server - OVERRIDE this in derivate of this 
		//  class to get control over view rendering when server response is received
		//  or CONNECT if more render function need to be added while retaining original
		//  render function
		// ----------------------------------------------------------------------	
		render: function(content,event){
			console.log("Rendering AxGrid View...EVENT = " + event);
			
			if(event == this.refreshUrl)
				if(content.model){
					this.renderGrid(content.model);
			}
			if( (event == this.addUrl) ||  (event == this.editUrl) ){				
				var node = document.createElement("div");
	        	document.body.appendChild(node);
	        	var d = new mydojo.dijix.FormDialog( {	id:"_gfd" , 
	        											title: event==this.addUrl? this.addDlgTitle : (event==this.editUrl? this.editDlgTitle : ""),
	        											action: event==this.addUrl? this.addDlgAction : (event==this.editUrl? this.editDlgAction : ""), 
	        											formStruct: content.formStruct,
	        											hasFile: event==this.addUrl? this.addDlgHasFile : (event==this.editUrl? this.editDlgHasFile : false),
	        											style : "width:" + ( event==this.addUrl? this.addDlgWidth : (event==this.editUrl? this.editDlgWidth : "360px") ) + ";"
	        										 } , node );
	        	var id = this.id;								 ;
				dojo.connect( d , "submit" , function(){ d.dispatch(id);} );
			}
		},
		// ======================================================================
		//	Render grid
		// ----------------------------------------------------------------------	
		renderGrid: function(content){
			this.gridWt.renderGrid(content);
			this.updateTotalRecs();
		},
		// ======================================================================
		//	Add row to grid
		// ----------------------------------------------------------------------
		addRow: function(rows){
			this.gridWt.addRow(rows);
		},
		// ======================================================================
		//	Clean up this widget
		// ----------------------------------------------------------------------	
		clean: function(){
			console.log("Running DbGrid.clean() function.")
			if(this.ttdWt)
				this.ttdWt.destroy();		
			this.toolWt.destroyDescendants();
			this.toolWt.destroy();
			this.gridWt.clean();
			this.gridWt.destroyDescendants();
			this.gridWt.destroy();
			this.footerWt.destroyDescendants();
			this.footerWt.destroy();
			this.bcWt.destroyDescendants();
			this.bcWt.destroy();
		},
		// ======================================================================
		//	Create toolbar
		// ----------------------------------------------------------------------
		createToolbar: function(){			
			var tb = new dijit.Toolbar({id:this.id+"_tb" , style:"height:32px"});						
			tb.startup();
			this.toolWt.domNode.appendChild(tb.domNode);
			for(var i = 0; i < this.toolbarStruct.length ; i++){
				switch(this.toolbarStruct[i]){
					case 'r':
						var btt = new dijit.form.Button({ id:this.id+"_refresh" , label:"Refresh" , iconClass:"navBarIcon iconRefresh" , showLabel:false });
						tb.addChild(btt);		
						dojo.connect(btt,"onClick",this,"rClicked");
						break;						
					case 'a':
						var btt = new dijit.form.Button({ id:this.id+"_add" , label:"Add" , iconClass:"navBarIcon iconAdd" , showLabel:false });
						tb.addChild(btt);		
						dojo.connect(btt,"onClick",this,"aClicked");
						break;						
					case 'e':
						var btt = new dijit.form.Button({ id:this.id+"_edit" , label:"Edit" , iconClass:"navBarIcon iconEdit" , showLabel:false });
						tb.addChild(btt);		
						dojo.connect(btt,"onClick",this,"eClicked");
						break;						
					case 'd':
						var btt = new dijit.form.Button({ id:this.id+"_delete" , label:"Delete" , iconClass:"navBarIcon iconDelete" , showLabel:false });
						tb.addChild(btt);		
						dojo.connect(btt,"onClick",this,"dClicked");
						break;																							
					case 'et':
						var btt = new dijit.form.Button({ id:this.id+"_empty" , label:"Empty Table" , iconClass:"navBarIcon iconEmpty" , showLabel:false });
						tb.addChild(btt);		
						dojo.connect(btt,"onClick",this,"etClicked");
						break;							
				}
			}
			
		},
		// ======================================================================
		//	Add a button to toolbar
		// ----------------------------------------------------------------------
		addButtonToToolbar: function(button){
			dijit.byId(this.id+"_tb").addChild(button);
		},
		// ======================================================================
		//	Toolbar Button Actions
		// ----------------------------------------------------------------------
		rClicked: function(){
			this.dispatch( this.refreshUrl );
		},
		// ----------------------------------------------------------------------		
		aClicked: function(){
			this.dispatch(this.addUrl);			
		},
		// ----------------------------------------------------------------------		
		eClicked: function(){
			var row = this.gridWt.grid.selection.getSelected()[0];			
			if( !(row == undefined) ){				
				var argument =	"&id="+this.gridWt.grid.model.getDatum(row,0);				
				this.dispatch( this.editUrl+argument );
			}else
				console.error("Need to select a row in the grid!!");
		},
		// ----------------------------------------------------------------------		
		dClicked: function(){
			var len = this.gridWt.grid.selection.getSelected().length;
			if(len >0){
				var str = "<table border=0 cellpadding=0 cellspacing=5 width=\"380px\">"+
						  " <tr><td width=2%><img src=\"images/questionIcon.png\"</td><td align=\"left\">" +
						  " <span class=errorTitle >Are you sure you want to delete?</span></td><td>" +			
						  " <tr><td colspan=\"2\" align=\"left\" style=\"border-top: 1px solid rgb(134, 182, 204); padding-top: 5px;\">" +
						  "	<button dojoType=\"dijit.form.Button\"  >Yes</button>&nbsp;" + 
						  " <button dojoType=\"dijit.form.Button\"  onClick=\"dijit.byId('_gd').hide();\">No</button>&nbsp;" +							
						  "</td></tr></table>";
				this.showDlg( "Confirm Delete" , str , null );								
				var butt = dojo.query("button" , "_gd")[0].id;
				dojo.connect(dijit.byId(butt), "onClick" , this , "confirmDelete");			
			}else
				console.error("Need to select a row in the grid!!");										
		},
		// ======================================================================
		//	Delete Confirmed
		// ----------------------------------------------------------------------
		confirmDelete: function(){			
			dijit.byId('_gd').hide();			
			var id = [];			
			for(var i = 0 ; i < this.gridWt.grid.selection.getSelected().length ; i++){
				var rowId 	= this.gridWt.grid.selection.getSelected()[i];
				id[i] = this.getCellValue(rowId,0);					
			}			
			var ids = { 'id': id };			
			this.dispatch(this.deleteUrl + "&" + dojo.objectToQuery(ids));
		},
		// ======================================================================
		//	Empty button on Toolbar clicked 
		// ----------------------------------------------------------------------
		etClicked: function(){
			var str = "<table border=0 cellpadding=0 cellspacing=5 width=\"380px\">"+
					  " <tr><td><img src=\"images/error2.png\"</td><td align=\"left\">" +
					  " <span class=errorMsgText >You are about to delete all records from table.<br>"  +
					  " The index column will be reset to start from 1.<br>Are you sure you want to continue?</span></td>" +			
					  " <tr><td colspan=\"2\" align=\"left\" style=\"border-top: 1px solid rgb(134, 182, 204); padding-top: 5px;\">" +
					  "	<button dojoType=\"dijit.form.Button\">Yes</button>&nbsp;" + 
					  " <button dojoType=\"dijit.form.Button\"  onClick=\"dijit.byId('_gd').hide();\">No</button>&nbsp;" +							
					  "</td></tr></table>";
			this.showDlg( "Empty Table" , str , null );				
			var butt = dojo.query("button" , "_gd")[0].id;
			dojo.connect(dijit.byId(butt), "onClick" , this , "empty");										
		},
		// ======================================================================
		//	Empty database table
		// ----------------------------------------------------------------------
		empty: function(){ 
			dijit.byId('_gd').hide();			
			this.dispatch( this.emptyUrl ); 
		},
		// ======================================================================
		//	Re Structure grid header
		// ----------------------------------------------------------------------
		reStruct: function(struct){			
			this.gridWt.reStruct( struct );
		},	
		// ======================================================================
		//	Clean the grid data
		// ----------------------------------------------------------------------
		clearGrid: function(){
			console.log("AxGrid.clearGrid()");
			this.gridWt.clearGrid();
			this.updateTotalRecs();
		},	
		// ======================================================================
		//	Update Total Records
		// ----------------------------------------------------------------------
		updateTotalRecs: function(){
			var val = this.gridWt.grid.model.count;
			this.trWt.innerHTML = val;			
			this.enableButtons(val);						
		},
		// ======================================================================
		//	Enable Toolbar Buttons - based on records absent/present
		// ----------------------------------------------------------------------
		enableButtons: function(val){
			if(val>0){
				if( typeof dijit.byId(this.id+"_edit") !="undefined")
					dijit.byId(this.id+"_edit").setAttribute('disabled',false);
				if( typeof dijit.byId(this.id+"_delete") !="undefined")	
					dijit.byId(this.id+"_delete").setAttribute('disabled',false);
				if( typeof dijit.byId(this.id+"_empty") !="undefined")	
					dijit.byId(this.id+"_empty").setAttribute('disabled',false);
			}
			else{
				if( typeof dijit.byId(this.id+"_edit") !="undefined")
					dijit.byId(this.id+"_edit").setAttribute('disabled',true);			
				if( typeof dijit.byId(this.id+"_delete") !="undefined")			
					dijit.byId(this.id+"_delete").setAttribute('disabled',true);
				if( typeof dijit.byId(this.id+"_empty") !="undefined")
					dijit.byId(this.id+"_empty").setAttribute('disabled',true);
			}
		},
		// ======================================================================
		//	Get total row in grid
		// ----------------------------------------------------------------------
		getRowCount:function(){
			return this.gridWt.grid.model.count;
		},
		// ======================================================================
		//	Get cell value at row,col
		// ----------------------------------------------------------------------
		getCellValue: function(row,col){
			return this.gridWt.getCellValue(row,col);
		}
});
